﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;

namespace DCT.Service.Restriction.Utility.Web
{
    public class WebAPIHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            WebAPIContext webapiContext = new WebAPIContext(context);
            IWebAPI webapi = this.CreateWebAPIHandler(webapiContext);
            if (webapi != null)
            {
                try
                {
                    webapi.Process(webapiContext);
                }
                catch (Exception exception)
                {
                    if (!(exception is ThreadAbortException))
                    {
                        this.ResponseWhenThrowException(webapiContext, exception);
                    }
                }
            }
            else
            {
                this.ResponseWhenWebAPIHandlerNull(webapiContext);
            }
        }

        protected virtual IWebAPI CreateWebAPIHandler(WebAPIContext context)
        {
            IWebAPI webapiHandler = null;

            foreach (var factory in globalFactories)
            {
                webapiHandler = factory.Create(context);
                if (webapiHandler != null)
                {
                    break;
                }
            }

            return webapiHandler;
        }

        protected virtual void ResponseWhenWebAPIHandlerNull(WebAPIContext context)
        {
            //webapi为null时的操作
            //throw new InvalidOperationException("创建IWebAPIHandler为Null：" + context.Request.Url.AbsoluteUri);
            context.Response.StatusCode = 404;
            context.Response.Write("api not find");
            context.Response.End();
        }

        protected virtual void ResponseWhenThrowException(WebAPIContext context, Exception exception)
        {
            throw exception;
        }

        private static List<IWebAPIFactory> globalFactories = new List<IWebAPIFactory>();

        public static List<IWebAPIFactory> Factories
        {
            get
            {
                return globalFactories;
            }
        }

        //在global
        //WebAPIHttpHandler.Factories.Add(DefaultWebAPIHandlerFactory.Init(new List<string>{
        //  "xx.xx.xx"
        //}));
    }
}
